import re
import sys
import requests
from download_k import get_text_from_url
from translate import proc_jp, proc_gpt
from ai import talk_to_ai


def get_menu():
    url = 'https://kakuyomu.jp/works/16817330658491004760'
    pattern = '{"__typename":"Episode","id":"([0-9]+)","title":"([^"]+)"'
    content = requests.get(url).text
    episodes = re.findall(pattern, content)
    last_one = episodes[-1]
    print(f"Last Episode is {last_one[1]}")
    download(last_one[0], last_one[1])


def download(id, title):
    print(f"Downloading episode id :{id}")
    url = f"https://kakuyomu.jp/works/16817330658491004760/episodes/{id}"
    content = get_text_from_url(url)
    jp_file = f'{title}.rtf'
    with open(jp_file, mode='w', encoding='utf-8') as f:
        f.write(content)
    proc_jp(jp_file)
    trans(title)

import os
def trans(title):
    reg_file = f'{title}.regular.rtf'
    translate_file = f"{title}.translated.rtf"
    final_file = f"{title}.txt"
    if os.path.exists(translate_file):
        pass
    else:
        with open(reg_file, mode='r', encoding='utf-8') as f:
            text = f.read()
        translated = talk_to_ai(text)
        with open(translate_file, mode='w', encoding='utf-8') as f:
            f.write(translated)

    final = proc_gpt(translate_file)
    with open(final_file, mode='w', encoding='utf-8') as f:
        f.write(final)


if __name__ == '__main__':
    arg1 = sys.argv[1] if len(sys.argv) > 1 else ''
    if arg1:
        trans(arg1)
    else:
        get_menu()
